package com.steven.nio.chat2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class ChatServer {

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //非阻塞
        serverSocketChannel.configureBlocking(false);
        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(4448));
        //注册到选择器上，接收模式
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            int select = selector.select();
            if(select >0){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey next = iterator.next();
                    if(next.isAcceptable()){
                        //当前连接的channel
                        SocketChannel channel = serverSocketChannel.accept();
                        //设置当前连接通道为非阻塞
                        channel.configureBlocking(false);
                        //注册当前通道到selector
                        channel.register(selector,SelectionKey.OP_READ);
                        System.out.println(channel.getRemoteAddress()+"上线了");
                    }else if(next.isReadable()){
                        //拿到当前需要读取的通道
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer allocate = ByteBuffer.allocate(1024);
                        //读取数据
                        try {
                            channel.read(allocate);
                        } catch (IOException e) {
                            System.out.println(channel.getRemoteAddress() + "离线");
                            //取消注册
                            next.cancel();
                            //关闭通道
                            channel.close();
                        }
                        String msg = new String(allocate.array()).trim();
                        System.out.println(channel.getRemoteAddress()+":"+msg);
                        //向其他客户端发送消息
                        //拿到所有的key
                        Set<SelectionKey> keys = selector.keys();
                        for (SelectionKey selectionKey:keys){
                            Channel selectableChannel = selectionKey.channel();
                            //判断是否是socketchannel
                            if(selectableChannel instanceof SocketChannel){
                                //转换类型
                                SocketChannel  dest = (SocketChannel) selectableChannel;
                                //写入数据
                                dest.write(ByteBuffer.wrap(msg.getBytes()));
                            }
                        }
                    }
                    iterator.remove();
                }
            }
        }

    }
}
